<script
	lang="ts"
	setup
>
import { infoGet, menusGet } from '@/api'
import LeftMenu from '@/components/LeftMenu.vue'
import { useUserStore } from '@/stores/user'
import { computed, h, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const loaded = ref(false)
const collapsed = ref(false) // 是否收起菜单
const parent = computed(() => {
	let matched: any = route.matched
	if (matched.length > 2) {
		return matched[matched.length - 2]
	} else {
		return matched[0]
	}
})

const menuList = [
	{
		key: 'logout',
		label: () => h('div', { style: { width: '120px' } }, '退出')
	}
];

onMounted(async () => {
	await getInfo()
	await getMenu()
	loaded.value = true
})

async function getInfo() {
	const { data } = await infoGet()
	if (data) {
		userStore.setUserInfo(data)
	}
}

async function getMenu() {
	const { code, data } = await menusGet()
	if (code === 200) {
		userStore.setMenu(data)
	}
}

async function onMenuClick(key: string | number) {
	if (key === 'logout') {
		const dialog = window.$dialog.warning({
			title: '提示',
			content: '确定要退出吗？',
			positiveText: '确定',
			negativeText: '取消',
			onPositiveClick: async () => {
				dialog.loading = true
				await userStore.logout()
				//router.replace({ path: 'login' })
                router.push('/login') // 直接跳转
				dialog.loading = false
			}
		})
	}
}
</script>

<template>
	<n-spin :show="!loaded">
		<n-layout
			class="layout"
			has-sider
		>
			<LeftMenu
				:collapsed="collapsed"
				@close="collapsed = true"
				@show="collapsed = false"
			/>
			<n-layout class="rightLayout">
				<header class="header">
					<div class="title">
						{{ parent.meta.title }}
					</div>
					<div class="right">
						<n-dropdown
							trigger="hover"
							:options="menuList"
							@select="onMenuClick"
						>
							<n-button style="width: 120px">{{ userStore.user.userName }}</n-button>
						</n-dropdown>
					</div>
				</header>
				<RouterView
					v-if="loaded"
					:key="route.fullPath"
				/>
			</n-layout>
		</n-layout>
	</n-spin>
</template>
<style
	lang="less"
	scoped
>
.layout {
	height: 100vh;

	.header {
		height: 60px;
		flex-shrink: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-left: 20px;
		border-bottom: 1px solid var(--border-color);

		.title {
			border-left: 4px solid var(--border-color);
			padding-left: 15px;
			line-height: 1;
		}

		.right {
			padding: 0 20px;
		}
	}
}
</style>
